/**
 * New node file
 */
/**
 * 渲染模板
 */
var fs = require('fs');
var VIEW_FOLDER = __dirname + '/../templates/';
var cache = [];

var render = function(viewname,data){
	var str = '';
	if(viewname){
		if(!cache[viewname]){
			str = fs.readFileSync(VIEW_FOLDER + viewname + '.html','utf8');
			cache[viewname] = compile(str);

		}
	}
	var html = cache[viewname](data,escape);
	return html;
};

//子文件方法
var preCompile = function(str){
	var files = {};
	var replaced = str.replace(/<%\s+(include.*)\s+%>/g,function(match,code){
		var partial = code.split(/\s/)[1];
		if(!files[partial]){
			files[partial] = fs.readFileSync(VIEW_FOLDER + partial + '.html','utf8');
		}
		
		return files[partial];
	});
	
	//多层嵌套，继续替换
	if (str.match(/<%\s+(include.*)\s+%>/)) {
		return preCompile(replaced);
	} else {
		return replaced;
	}
}

var escape = function(html){
	return String(html)
		.replace(/&(?!\w+;)/g,'&amp;')
		.replace(/</g,'&lt;')
		.replace(/>/g,'&gt;')
		.replace(/"/g,'&quot;')
		.replace(/'/g,'&#039;');
};

var compile = function(str) {
	// 预解析子模板；
	str = preCompile(str);

	var tpl = str.replace(/\r\n/g,'\\r\\n')
		.replace(/<%=([\s\S]+?)%>/g,function(match,code){
			//需要转义的情况
			return "' + escape(" + code + ") + '";
		}).replace(/<%-([\s\S]+?)%>/g,function(match,code){
			//不转义的情况
			return "'+" + code + "+'";
		}).replace(/<%([\s\S]+?)%>/g,function(match,code){
			//可执行代码
			return "';\r\n" +code+ "\ntpl += '";
		}).replace(/\'\r\n/gm,'\'')
		.replace(/\r\n\'/gm, '\'');
	
	tpl = "tpl = '" + tpl + "';";
	
	//转换空行
	tpl = tpl.replace(/''/g,'\'\\n\'');
	tpl = 'var tpl = "";\nwith(obj || {}) {\n' +tpl+ '\n}\nreturn tpl;';
	return new Function('obj','escape', tpl);
};

module.exports = render;